import { isUndefined } from "@ct0/functions";
import type { NestFilterConditions, NestFilterField } from "./type";

export function toPostgresWhereString(conditions: NestFilterConditions) {
  let where = "";
  return where;
}

export function toElasticWhereString(conditions: NestFilterConditions) {
  let where = "";
  return where;
}

import type { NestFilterOperator } from "./type";

export const OPERATOR_NAMES: Record<NestFilterOperator, string> = {
  "=": "等于",
  "!=": "不等于",
  ">": "大于",
  ">=": "大于等于",
  "<": "小于",
  "<=": "小于等于",
  in: "在其中",
  "not in": "不在其中",
  between: "范围内",
  contain: "包含",
  "not contain": "不包含",
  "starts with": "开始为",
  "ends with": "结尾为",
  "is null": "是否为空",
  regexp: "正则",
  subnet: "在子网",
};

export function getOperatorsByField(field: NestFilterField) {
  // 首先判断是否有自定义操作符，如果没有则根据类型自动匹配
  let { type, component, operators } = field;

  if (!operators) {
    //   支持几种操作符，是根据 type 和 component 共同决定的
    if (type == "string") {
      if (component == "input")
        operators = [
          "=",
          "!=",
          "contain",
          "not contain",
          "starts with",
          "ends with",
          "is null",
          "regexp",
        ];
      if (component == "select")
        operators = ["=", "!=", "in", "not in", "is null"];
      if (component == "ip")
        operators = [
          "=",
          "!=",
          "starts with",
          "ends with",
          "regexp",
          "subnet",
          "in",
          "between",
          "is null",
        ];
      if (component == "date" || component == "datetime")
        operators = ["between", "is null"];
      if (component == "input_array") operators = ["in"];
    }
    if (type == "number") {
      if (component == "input")
        operators = ["=", "!=", ">", ">=", "<=", "<", "between", "is null"];
      if (component == "select")
        operators = ["=", "!=", "in", "not in", "is null"];
      if (component == "date" || component == "datetime")
        operators = ["between", "is null"];
      if (component == "input_array") operators = ["in"];
    }
    if (type == "boolean") {
      operators = ["=", "is null"];
    }
  }

  if (!operators)
    throw Error("嵌套筛选的字段没有匹配到操作符 " + JSON.stringify(field));

  return operators.map((i) => ({
    label: OPERATOR_NAMES[i] || i,
    value: i,
  }));
}

export const getTimestamp = (t?: string | number) => {
  if (isUndefined(t)) return undefined;
  const ts = new Date(t).valueOf();
  return isNaN(ts) ? undefined : ts;
};
